<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="5" :lg="6" :md="8" :sm="24">
            <a-form-item label="客户名称">
              <a-input placeholder="请输入客户名称" v-model="queryParam.customerName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="8" :sm="24">
            <a-form-item label="客户电话">
              <a-input placeholder="请输入客户电话" v-model="queryParam.customerPhone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item label="状态">
              <a-select placeholder="请选择状态" v-model="queryParam.status" allowClear>
                <a-select-option value="0">待处理</a-select-option>
                <a-select-option value="1">已处理</a-select-option>
                <a-select-option value="2">已完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item label="物流信息">
              <a-select placeholder="请选择物流信息" v-model="queryParam.logisticsType" allowClear>
                <a-select-option value="0">到付</a-select-option>
                <a-select-option value="1">寄付</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item label="门类型">
              <a-select placeholder="请选择门类型" v-model="queryParam.type" allowClear>
                <a-select-option value="0">推拉</a-select-option>
                <a-select-option value="1">平开</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item label="询单日期">
              <a-date-picker
                v-model="queryParam.inquiryDate"
                style="width: 100%"
                format="YYYY-MM-DD"
                placeholder="请选择询单日期"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="8" :sm="24">
            <a-form-item label="收货地址">
              <a-input placeholder="请输入收货地址" v-model="queryParam.deliveryAddress"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons" style="display: flex; align-items: center">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('询单表')">导出</a-button>
      <a-button type="primary" icon="upload" @click="handleImportExcel">导入</a-button> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a> 项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="rowSelection"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :scroll="{ x: 1260 }"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="logisticsTypeSlot" slot-scope="text">
          <a-tag v-if="text == 0" color="orange">到付</a-tag>
          <a-tag v-else-if="text == 1" color="green">寄付</a-tag>
        </template>

        <template slot="typeSlot" slot-scope="text">
          <a-tag v-if="text == 0" color="blue">推拉</a-tag>
          <a-tag v-else-if="text == 1" color="cyan">平开</a-tag>
        </template>

        <template slot="statusSlot" slot-scope="text">
          <a-tag v-if="text == 0" color="red">待处理</a-tag>
          <a-tag v-else-if="text == 1" color="orange">已处理</a-tag>
          <a-tag v-else-if="text == 2" color="green">已完成</a-tag>
        </template>

        <template slot="action" slot-scope="text, record">
          <template v-if="record.status == 2">
            <a @click="handleDetail(record)">详情</a>
          </template>
          <template v-else>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDetail(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="handleInquiry(record)">询单</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要完结此询单吗?" @confirm="() => handleComplete(record.id)">
              <a style="color: #52c41a">完结</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>

    <inquiry-modal ref="modalForm" @ok="modalFormOk"></inquiry-modal>
    <inquiry-detail-modal ref="inquiryDetailModal" @ok="inquiryDetailModalOk"></inquiry-detail-modal>
    <inquiry-item-modal ref="inquiryItemModal" @ok="inquiryItemModalOk"></inquiry-item-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import InquiryModal from './modules/InquiryModal'
import InquiryDetailModal from './modules/InquiryDetailModal'
import InquiryItemModal from './modules/InquiryItemModal'

export default {
  name: 'InquiryList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    InquiryModal,
    InquiryDetailModal,
    InquiryItemModal,
  },
  data() {
    return {
      description: '询单管理页面',
      advanced: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName',
          width: 140,
        },
        {
          title: '客户电话',
          align: 'center',
          dataIndex: 'customerPhone',
          width: 140,
        },
        {
          title: '收货地址',
          align: 'center',
          dataIndex: 'deliveryAddress',
          width: 250,
          ellipsis: true,
        },
        {
          title: '物流信息',
          align: 'center',
          dataIndex: 'logisticsType',
          width: 100,
          scopedSlots: { customRender: 'logisticsTypeSlot' },
        },
        {
          title: '门类型',
          align: 'center',
          dataIndex: 'type',
          width: 90,
          scopedSlots: { customRender: 'typeSlot' },
        },
        {
          title: '询单日期',
          align: 'center',
          dataIndex: 'inquiryDate',
          width: 120,
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 90,
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '总价',
          align: 'center',
          dataIndex: 'totalPrice',
          width: 100,
          customRender: function (text) {
            return text ? `¥${parseFloat(text).toFixed(2)}` : '¥0.00'
          },
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          width: 180,
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 220,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/oms/inquiry/list',
        delete: '/oms/inquiry/delete',
        deleteBatch: '/oms/inquiry/deleteBatch',
        exportXlsUrl: '/oms/inquiry/exportXls',
        importExcelUrl: '/oms/inquiry/importExcel',
        complete: '/oms/inquiry/complete',
      },
      dictOptions: {},
      superFieldList: [],
      rowSelection: {
        selectedRowKeys: [],
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'customerName', text: '客户名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'customerPhone', text: '客户电话', dictCode: '' })
      fieldList.push({ type: 'string', value: 'deliveryAddress', text: '收货地址', dictCode: '' })
      fieldList.push({ type: 'int', value: 'logisticsType', text: '物流信息', dictCode: 'logistics_type' })
      fieldList.push({ type: 'date', value: 'inquiryDate', text: '询单日期', dictCode: '' })
      fieldList.push({ type: 'int', value: 'status', text: '状态', dictCode: 'inquiry_status' })
      fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
      this.superFieldList = fieldList
    },
    searchQuery() {
      // 处理日期格式化
      let params = { ...this.queryParam }
      if (params.inquiryDate && typeof params.inquiryDate === 'object') {
        // 格式化日期为 YYYY-MM-DD 格式
        const date = new Date(params.inquiryDate)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        params.inquiryDate = `${year}-${month}-${day}`
      }
      this.queryParam = params
      this.loadData(1)
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleDetail(record) {
      this.$refs.inquiryDetailModal.detail(record)
    },
    handleInquiry(record) {
      this.$refs.inquiryItemModal.edit(record)
    },
    inquiryDetailModalOk() {
      this.loadData()
    },
    inquiryItemModalOk() {
      this.loadData()
    },
    handleComplete(id) {
      const that = this
      this.$http
        .put(this.url.complete + '/' + id)
        .then((res) => {
          if (res.success) {
            that.$message.success('询单完结成功！')
            that.loadData()
          } else {
            that.$message.error(res.message || '操作失败')
          }
        })
        .catch((error) => {
          console.error('完结询单失败:', error)
          that.$message.error('完结询单失败，请稍后重试')
        })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
